package com.saas.tenant.tenantConfig;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.saas.tenant.tenantConfig.TenantContextHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @auther Jiang Tian
 * @date 2025/3/3
 * @apiNote
 **/
@WebFilter("/*")
public class TenantFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        String tenantId = req.getHeader("X-Tenant-Id");

        if (StringUtils.isNotBlank(tenantId)) {
            TenantContextHolder.setTenantId(Long.valueOf(tenantId));
        }else {
            TenantContextHolder.setTenantId(1L);
        }

        try {
            chain.doFilter(request, response);
        } finally {
            TenantContextHolder.clear();
        }

    }

}
